package com.spark.route.config;

import com.spark.route.handler.LocationHandler;
import com.spark.route.handler.PersonHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerResponse;

import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.servlet.function.RequestPredicates.*;


@Configuration
public class Router {
    @Bean
    public RouterFunction<ServerResponse> fooFunction() {
        return RouterFunctions.route()
                .GET("/v1/userinfo/foo", request -> ServerResponse.ok()
                        .body("qq.cn"))
                .build();
    }

    /**
     * 如果没有plan参数，则会报404
     * http://localhost:8080/v1/userinfo/predicate?plan=
     *
     * @return
     */
    @Bean
    public RouterFunction<ServerResponse> predicateFunction() {
        return RouterFunctions.route()
                .GET("/v1/userinfo/predicate",
                        request -> request.param("plan").isPresent(),
                        request -> ServerResponse.ok().body("felord.cn"))
                .build();
    }

    @Bean
    public RouterFunction<ServerResponse> routerFunctions(PersonHandler personHandler, LocationHandler locationHandler) {
        return RouterFunctions.route(GET("/people/{id}").and(accept(APPLICATION_JSON)), personHandler::get)
                .andRoute(GET("/people").and(accept(APPLICATION_JSON)), personHandler::all)
                .andRoute(POST("/people").and(accept(APPLICATION_JSON)).and(contentType(APPLICATION_JSON)), personHandler::post)
                .andRoute(PUT("/people/{id}").and(accept(APPLICATION_JSON)).and(contentType(APPLICATION_JSON)), personHandler::put)
                .andRoute(DELETE("/people/{id}"), personHandler::delete)
                .andRoute(GET("/people/country/{country}").and(accept(APPLICATION_JSON)), personHandler::getByCountry)
                .andRoute(GET("/locations/{id}").and(accept(APPLICATION_JSON)), locationHandler::get);
    }
}
